package ex01.pyrmont;

import java.io.*;

/**
 * @author: 顶风少年
 * @Description:
 * @date: 2023/4/28
 **/
public class Response {
    private static final int BUFFER_SIZE = 1024;
    Request request;
    OutputStream output;

    public Response(OutputStream output) {
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    //从request获取用户需要的文件,然后从静态目录
    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists()) {
                fis = new FileInputStream(file);
                //将静态资源中的数据读取
                StringBuilder sb = new StringBuilder();
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch != -1) {
                    sb.append(new String(bytes, 0, ch));
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
                //拼接上静态资源
                String message = "HTTP/1.1 200 OK\r\n" +
                        "Content-Type: text/html\r\n" +
                        "\r\n" +
                        sb.toString();
                //写入客户端
                output.write(message.getBytes());
            } else {
                //文件不存在返回错误信息
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                output.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

}
